<template>
  <div
    class="ct-pager"
    :class="{ [`ct-pager-type-${type}`]: type, [`ct-pager-size--${size}`]: size }"
  >
    <!-- 首页 -->
    <a :class="currentPage === 1 ? 'disabled' : ''" @click="currentPageHandler(1)">首页</a>
    <!-- 上一页 -->
    <a :class="currentPage == 1 ? 'disabled' : ''" @click="backPageHandler">
      <ct-icon icon="angles-left"></ct-icon>
    </a>
    <!-- 显示页码 -->
    <a v-if="pageTotal > 10 && currentPage >= 5" @click="currentPageHandler(1)">1</a>
    <a v-if="pageTotal > 10 && currentPage >= 5">
      <ct-icon icon="ellipsis" size="sm"></ct-icon>
    </a>
    <a
      v-for="t in pagerLis"
      :key="t"
      :class="t === currentPage ? 'active' : ''"
      @click="currentPageHandler(t)"
      >{{ t }}</a
    >
    <a v-if="pageTotal > 10 && currentPage < pageTotal - 3">
      <ct-icon icon="ellipsis" size="sm"></ct-icon>
    </a>
    <a
      v-if="pageTotal > 10 && currentPage < pageTotal - 3"
      @click="currentPageHandler(pageTotal)"
      >{{ pageTotal }}</a
    >
    <!-- 下一页 -->
    <a :class="currentPage == pageTotal ? 'disabled' : ''" @click="nextPageHandler">
      <ct-icon icon="angles-right"></ct-icon>
    </a>
    <!-- 尾页 -->
    <a :class="currentPage == pageTotal ? 'disabled' : ''" @click="currentPageHandler(pageTotal)"
      >尾页</a
    >

    <!-- 总页码 -->
    <span>共 {{ pageTotal }} 页</span>
  </div>
</template>
<script setup>
import { computed } from 'vue'
import propsOptions from './props'
defineOptions({
  name: 'CtPager',
})
const props = defineProps(propsOptions)

const pageTotal = computed(() => Math.ceil(props.total / props.pageSize))

const pagerLis = computed(() => {
  const renderPage = []
  if (pageTotal.value <= 10) {
    // 全部页码
    for (let i = 1; i <= pageTotal.value; i++) {
      renderPage.push(i)
    }
  } else {
    // 此时 总页码数大于可渲染页码数， 无法全部渲染
    if (props.currentPage < 5) {
      // 1. 当前选中页比较靠前 【1】2 3 4 5 6 7 8 ... 15
      for (let i = 1; i <= 5; i++) {
        renderPage.push(i)
      }
    } else if (props.currentPage > pageTotal.value - 3) {
      // 2. 当前选中页靠后 ... 6 7 8 9 10 11 12 [13] 14 15
      for (let i = pageTotal.value - 3; i <= pageTotal.value; i++) {
        renderPage.push(i)
      }
    } else {
      // 3. 当前选中页在中间位置 ... 5 6 7 [8] 9 10 11 ... 15
      for (let i = props.currentPage - 2; i <= props.currentPage + 3; i++) {
        renderPage.push(i)
      }
    }
  }
  console.log(renderPage)
  return renderPage
})

const emit = defineEmits(['current-change'])
function currentPageHandler(val) {
  emit('current-change', val)
}

function nextPageHandler() {
  if (props.currentPage < pageTotal.value) {
    emit('current-change', props.currentPage + 1)
  }
}

function backPageHandler() {
  if (props.currentPage > 1) {
    emit('current-change', props.currentPage - 1)
  }
}
</script>
<style lang="scss" scoped></style>
